package cn.wolfcode.crm.util;

import cn.wolfcode.crm.domain.SystemLog;
import cn.wolfcode.crm.service.ISystemLogService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.JoinPoint;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;

public class SystemLogUtils {

    @Autowired
    private ISystemLogService systemLogService;

    /*记录系统日志的方法,JoinPoint为当前的类,方法,参数等封装*/
    public void writeLog(JoinPoint joinPoint) throws JsonProcessingException {
        //获取当前访问的方法名称
        String name = joinPoint.getSignature().getName();

        /*当记录日志时,访问的SystemLog的时候不需要记录到日志,否则死循环,以及查询时不用记入*/
        if(!(joinPoint.getTarget() instanceof ISystemLogService)&&!(name.startsWith("query")
                ||name.startsWith("select")||name.startsWith("get")||name.startsWith("list"))){
            SystemLog log = new SystemLog();
            log.setOpTime(new Date());
            /*当前操作用户*/
            log.setOpUser(UserContext.getCurrentUser());
            /*用户的Ip,Request中可以取到*/
            log.setOpIp(UserContext.getRequest().getRemoteAddr());

            /*操作的类和方法,用AOP的类JoinPoint*/
            /*类名*/
            String className = joinPoint.getTarget().getClass().getSimpleName();
            /*方法名*/
            String methodName = joinPoint.getSignature().getName();
            log.setFunction(className+":"+methodName);

            /*文件上传的参数暂时不做记录*/
            try {
                if(!(joinPoint.getSignature().getName().equals("importData"))){
                    /*方法参数,joinPoint的到的是数组,转为json字符串*/
                    String json = new ObjectMapper().writeValueAsString(joinPoint.getArgs());
                    log.setParams(json);
                    /*保存日志到数据库*/
                    systemLogService.insert(log);
                }
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }

        }
    }
}
